<?php
namespace app\admin\controller;


use app\common\model\GoodsAttrsModel;
use app\common\model\GoodsBrandModel;
use app\common\model\GoodsCateModel;
use app\common\model\GoodsModel;
use app\common\model\GoodsSkuPriceModel;
use app\common\service\Config;
use app\common\service\Excel;
use app\listener\SyncStock;
use crmeb\zyx\Zyx;
use GuzzleHttp\Exception\RequestException;
use think\Collection;
use think\Paginator;

class Goods extends Common {

    protected $ignore_action = ['import'];
    //获取列表
    public function goodsAttrsModel_lists()
    {
        $list =[];
        GoodsAttrsModel::getAllCate()->each(function($item)use(&$list){
            $info = $item->apiFullInfo();
            $info['child_list'] = [];
            $linkChild = $item->getRelation('linkChild');
            foreach ($linkChild as $vo){
                $childInfo = $vo->apiFullInfo();
                $childInfo['child_list'] = [];
                $linkChild2 = $vo->getRelation('linkChild');
                foreach ($linkChild2 as $child2){
                    $childInfo['child_list'][] =  $child2->apiFullInfo();
                }
                $info['child_list'][]  = $childInfo;
            }
            array_push($list,$info);
        });
        return $this->_resData(1,'获取成功',['list'=>$list]);
    }




//获取列表
    public function goodsCateModel_lists()
    {
        $list =[];
        GoodsCateModel::getAllCate()->each(function($item)use(&$list){
            $info = $item->apiFullInfo();
            $info['child_list'] = [];
            $linkChild = $item->getRelation('linkChild');
            $child_list = [];
            foreach ($linkChild as $vo){
                array_push($child_list,$vo->apiFullInfo());
            }
            $info['child_list'] = $child_list;
            array_push($list,$info);
        });
        return $this->_resData(1,'获取成功',['list'=>$list]);
    }

    public function modifyStock()
    {
        $ids = input('ids');
        $stock = input('stock',0,'intval');

        $optModel = input('optModel','','trim');
        $optQuery = input('optQuery','','trim');

        $mod_data['stock'] = $stock;
        if($optModel=='all'){

            $info = GoodsModel::getPageData($optQuery);
            $optQuery['limit'] = $info->total();
            $all_goods_ids = [];
            GoodsModel::getPageData($optQuery)->each(function($item)use($mod_data,&$all_goods_ids){
                $all_goods_ids[] = $item['id'];
                $item->setAttrs($mod_data);
                $item->save();
            });
            GoodsSkuPriceModel::where(['gid'=>$all_goods_ids])->update($mod_data);
        }elseif(!empty($ids) && is_array($ids)){
            foreach ($ids as $id){
                GoodsModel::where(['id'=>$id])->update($mod_data);
                GoodsSkuPriceModel::where(['gid'=>$id])->update($mod_data);
            }
        }
        return $this->_resData(1,'操作成功');
    }
    public function modifyTags()
    {
        $php_input = input();
        try{
            GoodsModel::modifyTags($php_input);
        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
        return $this->_resData(1,"操作成功");



    }



    public function import()
    {
        $show_info = 0;
        $input_data = input();
        $is_cover = input('is_cover',0,'intval'); //是否覆盖原来的数据

        if(!isset($input_data['file'])){
            $show_info = 1;
            $path = (new \app\common\service\Upload(0))->upload('xlsx',['abs_path'=>1]);
//        dump($path);exit;
        }else{
            $path = $input_data['file'];
        }

        $data = Excel::readLine($path);
//        dump($data);exit;
        //查询商品分类
//        $goods_cate = GoodsCateModel::where(['pid'=>0])->column('id','name');
        //删除表头
        $headers = array_shift($data);
        $headers_flip = array_flip($headers);

        $name_excel_index = function($header)use($headers_flip){
            return $headers_flip[$header]??-1;
        };

        //查询所有已存在的编号
        $check_no = []; //序号查询的编号
        $all_temp_no = GoodsModel::column('id','temp_no');
        $exist_temp_no = [];
        $all_goods = $all_sku = $all_sku_info = [];

        /*
         *
         * */
        $root_path = root_path();
        $upload_qiniu_state = \app\common\service\Upload::getUploadQiniuState();
        $upload_qiniu_info = \app\common\service\Upload::info("upload_goods");

        $save_img_fnc = function($url)use($root_path,$upload_qiniu_state,$upload_qiniu_info){
            if(empty($url))return "";
            return $url;
            $save_path = "/uploads/goods/import_".md5($url).'.png';
            $abs_path = $root_path.$save_path;
            if(!file_exists($abs_path)){
                file_put_contents($abs_path, file_get_contents($url));
            }

            //上传七牛
            if($upload_qiniu_state){
                $url = $upload_qiniu_info['url'];
                $data = $upload_qiniu_info['data']??[];
                $multipart = [];
                foreach ($data as $item=>$value){
                    array_push($multipart,[
                        'name'=>$item,
                        'contents'=>$value,
                    ]);
                }
                array_push($multipart,[
                    'name' => 'file',
                    'contents' => fopen($abs_path, 'r')
                ]);
                try{
                    $client = new \GuzzleHttp\Client();
                    $response = $client->request("post", $url, [
                        'verify'=>false,
                        'multipart' => $multipart
                    ]);
                    $result = $response->getBody()->getContents(); // '{"id": 1420053, "name": "guzzle", ...}'
                }catch (RequestException $e){
                    $result = $e->getResponse()->getBody()->getContents();
                }catch (\Exception $e){
                    $result = "{'errmsg':'{$e->getmessage()}'}";
                }
                $result_data = json_decode($result,true);
                if(!isset($result_data['error'])){
                    $json_data = $result_data['data'];

                    return $json_data['key']??'';
                }else{
                    return "";
                }

            }else{
                return request()->domain().$save_path;
            }


        };


        foreach ($data as $item){
            $temp_no =  trim($item[$name_excel_index('Handle')]??'');
            if(array_key_exists($temp_no, $all_temp_no)){
                if(!in_array($temp_no,$exist_temp_no)){
                    $exist_temp_no[] = $temp_no;
                }
                if(empty($is_cover)){ //是否覆盖
                    continue;
                }
            }
            $variant_sku =  trim($item[$name_excel_index('Variant SKU')]??'');
            $image_src = $save_img_fnc(trim($item[$name_excel_index('Image Src')]??''));
            $variant_image = $save_img_fnc(trim($item[$name_excel_index('Variant Image')]??''));
            $info = [
                'temp_no'=>$temp_no,
                'name'=> trim($item[$name_excel_index('Title')]??''),
                'content'=>trim($item[$name_excel_index('Body (HTML)')]??''),
                'vendor'=>trim($item[$name_excel_index('Vendor')]??''),
                'type'=>trim($item[$name_excel_index('Standardized Product Type')]??''),
                'custom_type'=>trim($item[$name_excel_index('Custom Product Type')]??''),
                'tags'=>trim($item[$name_excel_index('Tags')]??''),
                'published'=>trim($item[$name_excel_index('Published')]??'')=='false'?2:1,
                'option1_name'=>trim($item[$name_excel_index('Option1 Name')]??''),
                'option1_value'=>trim($item[$name_excel_index('Option1 Value')]??''),
                'option2_name'=>trim($item[$name_excel_index('Option2 Name')]??''),
                'option2_value'=>trim($item[$name_excel_index('Option2 Value')]??''),
                'option3_name'=>trim($item[$name_excel_index('Option3 Name')]??''),
                'option3_value'=>trim($item[$name_excel_index('Option3 Value')]??''),
                'variant_sku'=>$variant_sku,
                'variant_grams'=>trim($item[$name_excel_index('Variant Grams')]??''),
                'variant_inventory_tracker'=>trim($item[$name_excel_index('Variant Inventory Tracker')]??''),
                'variant_inventory_qt'=>trim($item[$name_excel_index('Variant Inventory Qty')]??''),
                'variant_inventory_policy'=>trim($item[$name_excel_index('Variant Inventory Policy')]??''),
                'variant_fulfillment_service'=>trim($item[$name_excel_index('Variant Fulfillment Service')]??''),
                'variant_price'=>trim($item[$name_excel_index('Variant Price')]??''),
                'variant_compare_at_price'=>trim($item[$name_excel_index('Variant Compare At Price')]??''),
                "variant_requires_shipping"=>trim($item[$name_excel_index('Variant Requires Shipping')]??''),
                "variant_taxable"=>trim($item[$name_excel_index('Variant Taxable')]??''),
                "variant_barcode"=>trim($item[$name_excel_index('Variant Barcode')]??''),
                "image_src"=>$image_src,
                "image_position"=>trim($item[$name_excel_index('Image Position')]??''),
                "image_alt_tText"=>trim($item[$name_excel_index('Image Alt Text')]??''),
                "gift_card"=>trim($item[$name_excel_index('Gift Card')]??''),
                "seo_title"=>trim($item[$name_excel_index('SEO Title')]??''),
                "seo_description"=>trim($item[$name_excel_index('SEO Description')]??''),
                "google_shopping_Google_product_category"=>trim($item[$name_excel_index('Google Shopping / Google Product Category')]??''),
                "googles_hopping_gender"=>trim($item[$name_excel_index('Google Shopping / Gender')]??''),
                "google_shopping_age_group"=>trim($item[$name_excel_index('Google Shopping / Age Group')]??''),
                "google_shopping_mpn"=>trim($item[$name_excel_index('Google Shopping / MPN')]??''),
                "google_shopping_ad_words_grouping"=>trim($item[$name_excel_index('Google Shopping / AdWords Grouping')]??''),
                "google_shopping_adwords_labels"=>trim($item[$name_excel_index('Google Shopping / AdWords Labels')]??''),
                "google_shopping_condition"=>trim($item[$name_excel_index('Google Shopping / Condition')]??''),
                "google_shopping_custom_product"=>trim($item[$name_excel_index('Google Shopping / Custom Product')]??''),
                "google_shopping_custom_label0"=>trim($item[$name_excel_index('Google Shopping / Custom Label 0')]??''),
                "google_shopping_custom_label1"=>trim($item[$name_excel_index('Google Shopping / Custom Label 1')]??''),
                "google_shopping_custom_label2"=>trim($item[$name_excel_index('Google Shopping / Custom Label 2')]??''),
                "google_shopping_custom_label3"=>trim($item[$name_excel_index('Google Shopping / Custom Label 3')]??''),
                "google_shopping_custom_label4"=>trim($item[$name_excel_index('Google Shopping / Custom Label 4')]??''),
                "variant_image"=>$variant_image,
                "variant_weight_unit"=>trim($item[$name_excel_index('Variant Weight Unit')]??''),
                "variant_tax_code"=>trim($item[$name_excel_index('Variant Tax Code')]??''),
                "cost_per_item"=>trim($item[$name_excel_index('Cost per item')]??''),
                "status"=>trim($item[$name_excel_index('Status')]??''),
            ];

            if(!isset($all_goods[$temp_no])){


                $img = array_filter([$info['image_src'],$info['variant_image']]);
                $sku_first_str = "";
                if(!empty($info['option1_value'])){
                    $sku_first_str .= '-'.$info['option1_value'];
                    if(!empty($info['option2_value'])){
                        $sku_first_str .= "-".$info['option2_value'];
                        if(!empty($info['option3_value'])){
                            $sku_first_str .= "-".$info['option3_value'];
                        }
                    }
                }

                $code_str = str_replace("$sku_first_str","",$info['variant_sku']);
                $code_arr = explode('-',$code_str);
                $code = array_pop($code_arr);
                $no = implode('-',$code_arr);
//                dump($sku_first_str,$code_arr,$code,$no,$info['variant_sku']);exit;
                $all_goods[$temp_no] = [
                    'temp_no'=>$info['temp_no'],
                    'img'=> $img,
                    'no'=>$no,
                    'code'=>$code,
                    'name'=>$info['name'],
                    'content'=>$info['content'],
                    'tags'=> $info['tags'],
                    'variant_grams'=>$info['variant_grams'],
                    'price'=>$info['variant_price'],
                    'published'=>$info['published'],
                    'sku'=>[],
                    'sku_info'=>[],
                ];
                //判断数据库是否还存在
                if($is_cover==1 && !empty($temp_no) && isset($all_temp_no[$temp_no])){
                    $all_goods[$temp_no]['id'] = $all_temp_no[$temp_no];
                }
            }

            $sku_len = 3;
            $sku_group_name = [];
            for ($i=1;$i<=$sku_len;$i++){
                $name_key = "option{$i}_name";
                $value_key = "option{$i}_value";
                if(!empty($info[$value_key])){
                    $name_key_value = $info[$name_key];
                    $value_key_value = $info[$value_key];
                    $sku_group_name[] = $value_key_value;
                    if(!isset($all_goods[$temp_no]['sku'][$i])){
                        $all_goods[$temp_no]['sku'][$i] = [
                            'name'=>$name_key_value,
                            'content'=>[],
                        ];
                    }
                    if(!in_array($value_key_value,$all_goods[$temp_no]['sku'][$i]['content'])){
                        $all_goods[$temp_no]['sku'][$i]['content'][] = $value_key_value;
                    }
                }
            }
            unset($info['temp_no'],$info['name'],$info['content'],$info['tags']);

            array_push($all_goods[$temp_no]['img'],$variant_image);
            $all_goods[$temp_no]['img'] = array_values(array_filter(array_unique($all_goods[$temp_no]['img'])));

            $info['sku_group_name'] = $sku_group_name;
            $all_goods[$temp_no]['sku_info'][] = $info;
        }

        if($is_cover){
            $tip_msg = 'excel总记录'.(count($all_goods)).'条;重复记录:'.count($exist_temp_no).'条';
        }else{
            $tip_msg = 'excel总记录'.(count($all_goods)+count($exist_temp_no)).'条;重复记录:'.count($exist_temp_no).'条';
        }
        if($show_info){
            return $this->_resData(1,$tip_msg,[
                'exist_no'=>$exist_temp_no,
                'file'=>$path,
            ]);
        }



        $upload_images = [];
        foreach ($all_goods as &$goods){
            if(!empty($goods['id'])){
                $model_goods = GoodsModel::findOrEmpty($goods['id']);
            }else{
                $model_goods = new GoodsModel();
            }

            $sku_keyword_names=[];
            if(!empty($goods['sku'])){
                $sku_content = array_column($goods['sku'],'content');
                foreach ($sku_content as $_key=>$content){
                    $sku_keyword_names = array_merge($sku_keyword_names,$content);
                }

            }
            $sku = [];
            foreach ($goods['sku'] as $item){
                $item['content']  = implode(',',$item['content']);
                $sku[] = $item;
            }
            $goods_tags = empty($goods['tags'])?null : preg_replace('/\s+/','',','.$goods['tags'].',');
            $model_goods->setAttrs([
                'temp_no' => $goods['temp_no'],
                'name' => $goods['name'],
                'tags' => $goods_tags,
                'no' => $goods['no'],
                'code' => $goods['code'],
                'img' => implode(',',$goods['img']),
                'content' => $goods['content'],
                'sku' => array_values($sku),
                'sku_keyword_names' => strtoupper(empty($sku_keyword_names)?'':','.implode(',',$sku_keyword_names)).',',
                'status' => $goods['published'],
                'widget' => empty($goods['variant_grams'])?0:$goods['variant_grams']*1000,
                'price' => $goods['price'],
                'og_price' => $goods['price'],
            ]);
//            dump($goods['sku_info']);exit;
            $model_goods->save();
            if(!empty($goods['id'])){
                //删除对应的sku
                GoodsSkuPriceModel::where(['gid'=>$goods['id']])->delete();
            }
            if(!empty($model_goods->getAttr('img'))){
                array_push($upload_images,[
                    'id'=>$model_goods['id'],
                    'images'=>$model_goods->getAttr('img'),
                    'upload_state'=>0,
                    'state'=>false,
                ]);
            }

            //创建sku
            $all_sku = [];
            foreach ($goods['sku_info'] as $skuInfo){
                $info = [
                    'gid'=>$model_goods['id'],
                    'name'=>empty($skuInfo['sku_group_name'])?null:implode(',',$skuInfo['sku_group_name']),
                    'img'=>$skuInfo['variant_image'],
                    'og_price'=>$skuInfo['variant_compare_at_price'],
                    'price'=>$skuInfo['variant_price'],
                    'stock'=>intval($skuInfo['variant_inventory_qt']),
                    'status'=>$goods['published'],
                ];
                $sku_model = new GoodsSkuPriceModel();
                $sku_model->setAttrs($info);
                $sku_model->save();
//                if(!empty($sku_model->getAttr('img'))){
//                    array_push($upload_images,[
//                        'sku_id'=>$sku_model['id'],
//                        'images'=>[$sku_model->getAttr('img')],
//                        'state'=>false,
//                    ]);
//                }

//                array_push($all_sku,$info);
            }
//            dump($all_sku);exit;
//            GoodsSkuPriceModel::insertAll($all_sku);

        }
//        dump($all_goods);exit;
        //查询所有
//        GoodsModel::insertAll($all_goods);

        return $this->_resData(1,$tip_msg,[
            'exist_no'=>$exist_temp_no,
            'upload_images'=>$upload_images,
        ]);
    }

    public function modifyImage()
    {
        $input_data = input();
        if(isset($input_data['sku_id'])){
            $sku_id = $input_data['sku_id'];
        }else{
            $id = input('id');
        }
        $og_qiniu_img = empty($input_data['og_qiniu_img']) || !is_array($input_data['og_qiniu_img']) ? [] : $input_data['og_qiniu_img'] ;

        $images = input('images');
        $images = empty($images) || !is_array($images)?[]:$images;

        $root_path = root_path();
        $upload_qiniu_state = \app\common\service\Upload::getUploadQiniuState();
        $upload_qiniu_info = \app\common\service\Upload::info("upload_goods");

        $save_img_fnc = function($url)use($root_path,$upload_qiniu_state,$upload_qiniu_info){
            if(empty($url))return "";
            $save_path = "/uploads/goods/import_".md5($url).'.png';
            $abs_path = $root_path.$save_path;
            if(!file_exists($abs_path)){
                file_put_contents($abs_path, file_get_contents($url));
            }

            //上传七牛
            if($upload_qiniu_state){
                $url = $upload_qiniu_info['url'];
                $data = $upload_qiniu_info['data']??[];
                $multipart = [];
                foreach ($data as $item=>$value){
                    array_push($multipart,[
                        'name'=>$item,
                        'contents'=>$value,
                    ]);
                }
                array_push($multipart,[
                    'name' => 'file',
                    'contents' => fopen($abs_path, 'r')
                ]);
                try{
                    $client = new \GuzzleHttp\Client();
                    $response = $client->request("post", $url, [
                        'verify'=>false,
                        'multipart' => $multipart
                    ]);
                    $result = $response->getBody()->getContents(); // '{"id": 1420053, "name": "guzzle", ...}'
                }catch (RequestException $e){
                    $result = $e->getResponse()->getBody()->getContents();
                }catch (\Exception $e){
                    $result = "{'errmsg':'{$e->getmessage()}'}";
                }
                $result_data = json_decode($result,true);
                if(!isset($result_data['error'])){
                    $json_data = $result_data['data'];
                    return $json_data['key']??'';
                }else{
                    return "";
                }

            }else{
                return request()->domain().$save_path;
            }


        };
        $save_img = [];
//        $og_qiniu_img = [];
        foreach ($images as $img) {
            if(!isset($og_qiniu_img[$img])){
                $qiniu_img = $save_img_fnc($img);
                if(empty($qiniu_img)){
                    return $this->_resData(1,"图片上传失败【 $img 】",['code'=>1]);
                }
                $og_qiniu_img[$img] = $qiniu_img;
            }else{
                $qiniu_img = $og_qiniu_img[$img];
            }
            $save_img[] = $qiniu_img;
        }

        if(!empty($save_img)){
            if(isset($sku_id)){
                GoodsSkuPriceModel::where(['id'=>$sku_id])->update([
                    'img'=>implode(',',$save_img)
                ]);
            }else{
                GoodsModel::where(['id'=>$id])->update([
                    'img'=>implode(',',$save_img)
                ]);
                foreach ($og_qiniu_img as $og=>$qiniu){
                    GoodsSkuPriceModel::where(['gid'=>$id,'img'=>$og])->update([
                        'img'=>$qiniu,
                    ]);
                }
            }
        }

        return $this->_resData(1,'操作成功',[
            'og_qiniu_img'=>$og_qiniu_img
        ]);
    }


}